package org.skipper.common.spring.cloud.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.skipper.common.Result;
import org.skipper.common.constant.CommonCodeEnum;
import org.springframework.core.annotation.Order;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author shoujian
 * Date: 2022-02-14
 * Time: 3:51 PM
 */
@Order(2)
@Aspect
public class IsSignAspect {

    private static final String HEADER_ATTRIBUTE_IS_SIGN = "isSign";

    @Pointcut("@annotation(org.skipper.common.spring.cloud.annotation.IsSign)")
    public void execute() {
    }

    @Around("execute()")
    public Object doAround(ProceedingJoinPoint pjp) {
        // 验证token
        if (!checkIsSign()) {
            return Result.createErrorMsg(CommonCodeEnum.SIGNATURE_INCORRECT.getCode(), CommonCodeEnum.SIGNATURE_INCORRECT.getMessage());
        }

        try {
            return pjp.proceed();
        } catch (Throwable e) {
            return Result.createErrorMsg(CommonCodeEnum.FAIL.getCode());
        }
    }

    /**
     * 检查是否已经通过签名验证
     * 逻辑如下：
     * 从请求头中获取isSign参数
     * 1. 如果isSign参数存在, 则直接返回isSign的结果
     * 2. 如果isSign参数不存在, 则认为为内部请求, 不需要做验证, 返回true
     */
    public static boolean checkIsSign() {
        // 从当前请求中获取请求头参数
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();

        String isLogin = request.getHeader(HEADER_ATTRIBUTE_IS_SIGN);
        if (isLogin != null) {
            isLogin = isLogin.trim().toLowerCase();
            return Boolean.parseBoolean(isLogin);
        }

        return true;
    }

}
